import React, { useState, useEffect } from 'react';
import { Tabs } from 'antd-mobile';
import axios from 'axios';
import styles from '../css/game.module.css'; // 引入 CSS Module
import defaultImg from '../assets/pandaback.png';
import hourse2 from '../assets/hourse.png';
import flower from '../assets/flower2.png';
import send from '../assets/send.png';
import tree from '../assets/tree.png';
import mine from '../assets/mine.png';
import love from '../assets/love.png';
import yan from '../assets/yan.png';
import { fetchStrategyData, fetchTravelData, fetchQuesData } from '../api/gameApi'; // 引入封装好的接口
import { useNavigate } from 'react-router-dom';
import { imgUrl } from '../config';
const GamePage = () => {
    const [activeTab, setActiveTab] = useState('strategy');
    const [data, setData] = useState([]);
    const [datas, setDatas] = useState([]);
    const [dataes, setDataes] = useState([]);
    const navigate = useNavigate();

    // 初始化加载数据
    // 在 GamePage.js 中修改 useEffect 部分
    useEffect(() => {
        // 获取攻略数据
        const fetchData = async () => {
            try {
                const strategyResponse = await fetchStrategyData(3);
                console.log('攻略列表', strategyResponse);
                setData(strategyResponse.data); // 注意这里改为 strategyResponse.data
            } catch (error) {
                console.error('获取攻略数据时出错:', error);
            }
        };

        // 获取游记数据
        const fetchTravels = async () => {
            try {
                const travelResponse = await fetchTravelData();
                console.log('游记列表', travelResponse);
                setDatas(travelResponse.data); // 注意这里改为 travelResponse.data
            } catch (error) {
                console.error('获取游记数据时出错:', error);
            }
        };

        // 获取问答数据
        const fetchQues = async () => {
            try {
                const quesResponse = await fetchQuesData();
                console.log('问答列表', quesResponse);
                setDataes(quesResponse.data); // 注意这里改为 quesResponse.data
            } catch (error) {
                console.error('获取问答数据时出错:', error);
            }
        };

        fetchData();
        fetchTravels();
        fetchQues();
    }, []);

    // 图片错误处理
    const handleImageError = (e, fallback) => {
        e.target.src = defaultImg; // 将 fallback 替换为 defaultImg
    };


    const aircraft = () => {
        const img = document.querySelector(`.${styles.aircraft} img`);
        if (img) {
            img.style.marginTop = "-2000px";
            img.style.transition = "all 2s";
            setTimeout(() => {
                navigate("/issue");
            }, 2000);
        }
    };

    // 详情页跳转
    const manyitem = (i, id) => {
        sessionStorage.setItem("game", JSON.stringify(data[i]));
        sessionStorage.setItem("gameimg", data[i].bannar);
        navigate("/strategy");
    };

    const manyitems = (i, id) => {
        sessionStorage.setItem("playid", id);
        sessionStorage.setItem("game", JSON.stringify(datas[i]));
        sessionStorage.setItem("gameimg", datas[i].banner);
        navigate("/strategys"); // 使用 navigate 函数跳转到 /strategys 页面
    };

    const quesition = (i, id) => {
        sessionStorage.setItem("quesdata", JSON.stringify(dataes[i]));
        navigate("/questionsDetails");
    };

    // 渲染攻略顶部内容
    const renderTops = () => {
        if (!data.length) return null;

        return (
            <div className={styles.bigimg} onClick={() => manyitem(0, data[0].id)}>
                <img
                    src={`${imgUrl}${data[0].img}`}
                    alt=""
                    onError={(e) => handleImageError(e, './img/10006.webp')}
                    style={{ objectFit: 'cover' }}
                />
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                    <b>{data[0].name}</b>
                    <span>{data[0].introduce}</span>
                </div>
            </div>
        );
    };

    // 渲染攻略列表
    const renderRander = () => {
        return data.slice(1).map((item, i) => (
            <div
                key={item.id}
                className={styles.item}
                onClick={() => manyitem(i + 1, item.id)}
            >
                <img
                    src={`${imgUrl}${item.img}`}
                    alt=""
                    onError={(e) => handleImageError(e, './img/10006.webp')}
                    style={{ objectFit: 'cover' }}
                />
                <div className={styles['item-font']}>
                    <b>{item.name}</b>
                    <p>{item.introduce}</p>
                    <div style={{
                        display: 'flex',
                        color: '#555555',
                        fontSize: '15px',
                        alignItems: 'center',
                        marginTop: '10px'
                    }}>
                        <img
                            style={{ width: '30px', height: '30px', borderRadius: '50%' }}
                            src={`${imgUrl}${item.avatar}`}
                            alt=""
                        />
                        <span style={{
                            marginLeft: '10px',
                            textOverflow: 'ellipsis',
                            overflow: 'hidden',
                            display: 'block',
                            whiteSpace: 'nowrap',
                            fontSize: '13px',
                            width: '100px'
                        }}>
                            {item.name}
                        </span>
                    </div>
                </div>
            </div>
        ));
    };

    // 渲染游记
    const renderPlayer = () => {
        return datas.map((item, i) => (
            <div
                key={item.id}
                className={styles.product}
                onClick={() => manyitems(i, item.id)}
            >
                <img
                    src={`${imgUrl}${item.cover}`}
                    alt=""
                    onError={(e) => handleImageError(e, './img/11b55354ba3f475f43fb31cb2515cc77.png')}
                />
                <p>{item.title}</p>
                <div className={styles.contenter}>
                    <div className={styles['strategy-one']}>
                        <img
                            src={`${imgUrl}${item.avatar}`}
                            alt=""
                            onError={(e) => handleImageError(e, 'https://img.tukuppt.com/png_preview/00/37/17/WtXEla7XWN.jpg!/fw/780')}
                        />
                        <span>{item.name || 'lv'}</span>
                    </div>
                    <div className={styles.discuss}>
                        <img src={love} alt="" />
                        <span>{item.number || 0}</span>
                    </div>
                </div>
            </div>
        ));
    };

    // 渲染问答
    const renderAsk = () => {
        return dataes.map((item, i) => (
            <div
                key={item.id}
                className={styles['answer-top']}
                onClick={() => quesition(i, item.id)}
            >
                <div className={styles['head-img']}>
                    <img
                        src={`${imgUrl}${item.avatar}`}
                        alt=""
                        onError={(e) => handleImageError(e, 'https://img.tukuppt.com/png_preview/00/37/17/WtXEla7XWN.jpg!/fw/780')}
                    />
                </div>
                <div className={styles['answer-con']}>
                    <b>{item.name}</b>
                    <span>{item.content}</span>
                    <div style={{
                        display: 'flex',
                        alignItems: 'center',
                        width: '100%',
                        height: '40px',
                        justifyContent: 'space-between'
                    }}>
                        <p>发布于{item.create_time}</p>
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                            <img className={styles.com} src={yan} alt="" />
                            <span style={{
                                marginTop: '20px',
                                marginLeft: '5px',
                                marginRight: '10px'
                            }}>
                                {item.number || 0}
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        ));
    };



    const navigateTo = (path) => {
        navigate(`/${path}`); // 使用 navigate 函数跳转到指定路径
    };

    return (
        <div style={{ backgroundColor: '#f4f4f4' }}>
            {/* 使用 Ant Design Mobile 的 Tabs 替换原有选项卡 */}
            <Tabs
                activeKey={activeTab}
                onChange={setActiveTab}
                style={{
                    '--active-line-color': '#2a82e4',
                    '--active-title-color': '#2a82e4'
                }}
            >
                <Tabs.Tab title="攻略" key="strategy">
                    <div className={styles.strategy} style={{ marginTop: '-15px' }}>
                        <div className={styles.content}>
                            {renderTops()}
                        </div>
                        <div className={styles.bigitem}>
                            {renderRander()}
                        </div>
                    </div>
                </Tabs.Tab>

                <Tabs.Tab title="游记" key="travel">
                    <div className={styles.travel}>
                        <div className={`${styles.player} ${styles['max_product']}`}>
                            {renderPlayer()}
                        </div>
                    </div>
                </Tabs.Tab>

                <Tabs.Tab title="问答" key="answer">
                    <div className={styles.answer}>
                        {renderAsk()}
                    </div>
                </Tabs.Tab>
            </Tabs>

            {/* 底部导航栏 */}
            <div className={styles.bottom}>
                <div className={styles.second} onClick={() => navigate("/home")}>
                    <img src={hourse2} alt="" />
                    <p style={{ color: '#000000' }}>首页</p>
                </div>
                <div className={styles.first}>
                    <img src={flower} alt="" />
                    <p style={{ color: '#FF5050' }}>攻略</p>
                </div>
                <div className={styles.plane} onClick={aircraft}>
                    <div className={styles.aircraft}>
                        <img src={send} alt="" />
                    </div>
                    <p style={{ marginTop: '33px', textAlign: 'center' }}>发布</p>
                </div>
                <div className={styles.first} onClick={() => navigate("/ranking")}>
                    <img src={tree} alt="" />
                    <p>排行榜</p>
                </div>
                <div className={styles.first} onClick={() => navigate("/mine")}>
                    <img src={mine} alt="" />
                    <p>我的</p>
                </div>
            </div>
        </div>
    );
};

export default GamePage;    